import { ExceptionFilter, Catch, ArgumentsHost, UnauthorizedException, HttpException } from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class ValidationExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    // 只有UnauthorizedException(401)保持原状态码，其他都返回200
    const isUnauthorized = exception instanceof UnauthorizedException;
    const status = isUnauthorized ? exception.getStatus() : 200;
    const errorResponse = exception.getResponse();

    // 格式化错误消息为字符串
    let errorMessage = '请求处理失败';
    if (typeof errorResponse === 'object' && 'message' in errorResponse) {
      const messages = errorResponse.message;
      if (Array.isArray(messages)) {
        errorMessage = messages.join('; ');
      } else if (typeof messages === 'string') {
        errorMessage = messages;
      }
    } else if (typeof errorResponse === 'string') {
      errorMessage = errorResponse;
    }

    // 使用response发送错误响应
    response.status(status).json({
      code: status,
      success: false,
      message: errorMessage,
      data: null
    });
  }
}